<template>
    <div class="reviseProduct">

        <el-tabs v-model="activeName" type="card">
            <el-tab-pane label="商品信息" name="商品信息">
                <el-form :model="formInline" :rules="rules" ref="formInline" class="demo-form-inline" label-width="120px" size="small" style="margin-top:20px;">
                    <el-row>
                        <el-col :span="9">
                            <el-form-item label="商品条码">
                                <el-input v-model="formInline.barCode" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="9" :offset="3">
                            <el-form-item label="商品名称" prop="title">
                                <el-input v-model="formInline.title" placeholder="商品名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="9">
                            <el-form-item label="商品规格" prop="spec">
                                <el-input v-model="formInline.spec" placeholder="商品规格"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="9" :offset="3">
                            <el-form-item label="库存单位" width="100%" prop="unit">
                                <el-select v-model="formInline.unit" placeholder="全部">
                                    <el-option
                                            v-for="item in formUnit"
                                            :key="item"
                                            :label="item"
                                            :value="item">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="9">
                            <el-form-item label="最小批发数" prop="fleetSales">
                                <el-input v-model.number="formInline.fleetSales" placeholder="最小批发数"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="9" :offset="3">
                            <el-form-item label="箱规" prop="perCarton">
                                <el-input v-model.number="formInline.perCarton" placeholder="箱规"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="9">
                            <el-form-item label="批发价（元）" prop="price" >
                                <el-input v-model.number="formInline.price" placeholder="批发价"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="9" :offset="3">
                            <el-form-item label="商品状态" prop="shelfState">
                                <el-radio-group v-model="formInline.shelfState">
                                    <el-radio :label="0">正常</el-radio>
                                    <el-radio :label="1">下架</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="21" style="text-align:center;margin-top:30px;">
                            <el-form-item size="mini">
                                <el-button type="primary" @click="editProduct('formInline')" plain>保存</el-button>
                                <router-link to="/product_list" class="btn-router" style="margin-left:10px;">
                                    <el-button type="success" plain>返回</el-button>
                                </router-link>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-tab-pane>

            <el-tab-pane label="商品图片" name="商品图片">

                <el-upload
                        ref="upload"
                        list-type="picture-card"
                        action="enjoylove/product/addProductPicture"
                        :before-upload="beforeAvatarUpload"
                        :auto-upload="true"
                        accept=".jpg,.png,.gif"
                        :data="productId"
                        :on-change="newhandleChange"
                        :on-success="newhandlesuccess"
                        :before-remove="beforeRemove"
                        :limit="5"
                        :file-list="fileList">
                    <i class="el-icon-plus"></i>
                </el-upload>

                <dl>
                    <dt>商品图片说明：</dt>
                    <dd>1、图片格式为.png、.jpg、.gif；每个商品最多可上传5张图片，每张图片大小不超过2MB；</dd>
                    <dd>2、商品图片以数字命名，图片名代表图片在应用中的显示顺序，第一张图片默认为商品主图片。</dd>
                    <dd style="text-align:center;margin:30px auto;">
                        <router-link to="/product_list" class="btn-router">
                            <el-button type="success" plain size="mini">返回</el-button>
                        </router-link>
                    </dd>
                </dl>

            </el-tab-pane>
        </el-tabs>

    </div>
</template>
<script>
  import util from '../../../common/js/util'
  import * as api from '../../../api/enjoylove_api'
  let imgDiv = document.getElementsByClassName('el-upload')

  export default {
    data() {
      var checkPerCarton = (rule, value, callback) => {
        if (value != ''&&value!=null) {
          if (!Number.isInteger(value)) {
            return callback(new Error('请输入整数'));
          } else {
            if (value > 10000000) {
              return callback(new Error('必须是8位以内整数'));
            } else {
              return callback();
            }
          }
        }else {
            return callback();
        }
      };
      return {
        result: '',
        productId: {
          id: '',
          picId: ''
        },
        activeName: '商品信息',     //tab当前项
        formInline: {},            //表单项
        formUnit: [],              //商品单位
        rules: {
          title: [{required: true, message: '商品名称不能为空', trigger: 'blur'}],
          spec: [{required: true, message: '商品规格不能为空', trigger: 'blur'}],
          fleetSales: [
            {required: true, message: '最小批发数量不能为空', trigger: 'blur'},
            {type: 'number', message: '数量必须为数字', trigger: 'blur'}
          ],
          perCarton: [{validator: checkPerCarton, trigger: 'blur'}],
          shelfState: [{required: true, trigger: 'blur'}],
          unit: [{required: true, trigger: 'blur'}],
          price: [{required: true, pattern: /^\d{1,8}(\.\d{1,2})?$/,message: '批发价最多2位小数，且不超过8位整数', trigger: 'blur'}]
        },
        dialogImageUrl: '',
        file: '',
        fileList: [],
        upIs: false

      }
    },
    methods: {

      beforeAvatarUpload (file, fileList) {
        console.log(fileList)
        var fileName=new Array()
        fileName =file.name.split('.');
        const extension = fileName[fileName.length-1] === 'jpg'
        const extension2 =  fileName[fileName.length-1]=== 'png'
        const extension3 =  fileName[fileName.length-1]=== 'gif'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!extension && !extension2 && !extension3) {
          this.$message({
            message: '上传图片只能是.jpg、.png、.gif格式!',
            type: 'warning'
          });
        }
        if (!isLt2M) {
          this.$message({
            message: '上传图片大小不能超过 2MB!',
            type: 'warning'
          });
        }

        if (extension || extension2 || extension3 && isLt2M == true) {

          let fd = new FormData()
          fd.append('file', file)

          return true
        }
        return extension || extension2 || extension3 && isLt2M
      },
      newhandlesuccess (res, file, fileList) {
        console.log(fileList)
        console.log(JSON.parse(res).data.attcId)
        fileList.forEach((val) => {
          if (!val.id) {
            val.id = JSON.parse(res).data.attcId
          }
        })

        let response = JSON.parse(file.response)
        if (response){
          this.$message({
            message: '保存成功！',
            type: 'success'
          });
        }else {
          this.$message({
            message: '保存失败！',
            type: 'warning'
          });
        }

      },
      newhandleChange (file, fileList) {
        let imgDiv = document.getElementsByClassName('el-upload')
        if (fileList.length > 4) {
          imgDiv[0].style.display = 'none'
        }else {
          imgDiv[0].style.display = 'inline-block'
        }
      },
      beforeRemove (file, fileList) {
        var that=this;
        return new Promise(function (resolve, reject) {
          that.$confirm('此操作将删除商品图片, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let para = {
              id: that.productId.id,
              attIds: file.id
            }
            api.deleteProductPicture(para).then((res) => {
              let datas = JSON.parse(res.data);
              if(datas.success){
                //成功
                that.$message.success('删除成功!')
                if ((fileList.length-1) == 5) {
                  imgDiv[0].style.display = 'none'
                }else {
                  imgDiv[0].style.display = 'inline-block'
                }
                resolve(true);
              }else {
                that.$message.error(datas.message);
                reject(true)
              }
            });
          }).catch(() => {
            that.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        });

      },
      /*newhandleremove (file, fileList) {

        this.$confirm('此操作将此分类里删除该商品, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let para = {
            id: this.productId.id,
            attIds: file.id
          }
          api.deleteProductPicture(para).then((res) => {
            let datas = JSON.parse(res.data);
            if(datas.success){
              //成功
              this.$message.success('删除成功!')
              if (fileList.length == 5) {
                imgDiv[0].style.display = 'none'
              }else {
                imgDiv[0].style.display = 'inline-block'
              }

            }else {
              this.$message.error(datas.message);
            }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },*/

      //商品修改
      editProduct (formName) {
        let para = {
          id: this.formInline.id,
          title: this.formInline.title,
          barCode: this.formInline.barCode,
          spec: this.formInline.spec,
          unit: this.formInline.unit,
          perCarton: this.formInline.perCarton,
          fleetSales: this.formInline.fleetSales,
          shelfState: this.formInline.shelfState,
          price: this.formInline.price
        };
          this.$refs[formName].validate((valid) => {
              if (valid) {
                  api.editProduct(para).then((res) => {

                      let datas = JSON.parse(res.data);
                      if(!datas.status){
                          if(datas.success){
                              let that = this
                              //成功
                              this.$message({
                                  message: '保存成功！',
                                  type: 'success',
                                  duration: 2000,
                                  onClose: function () {
                                      that.activeName = '商品图片';
                                  }
                              });

                          }else {
                              this.$message.error(datas.message);
                          }
                      }else{
                          if(datas.status == 401){
                              this.$router.push('/login');
                          }
                          this.$message(res.data.msg);
                      }

                  });
              } else {
                  console.log('error submit!!');
                  return false;
              }
          });

      },

      //商品详情查询
      getProduct () {
        let para = {
          id: this.productId.id
        };

        api.getProduct(para).then((res) => {

          let datas = JSON.parse(res.data);
          console.log(datas)
          if(!datas.status){
            if(datas.success){
              //成功
              this.formInline = datas.data.product;
              if(this.formInline.price){
                  this.formInline.price = this.formInline.price/100;
              }
              datas.data.pics.forEach((val) => {
                this.fileList.push({
                  id: val.id,
                  name: val.title,
                  url: 'https://forca.yjlbld.com'+val.url
                })
              })
              console.log(datas.data.pics.length)
              if (datas.data.pics.length > 4) {
                imgDiv[0].style.display = 'none'
              }else {
                imgDiv[0].style.display = 'inline-block'
              }

            }else {
              this.$message.error(datas.message);
            }
          }else{
            if(datas.status == 401){
              this.$router.push('/login');
            }
            this.$message(res.data.msg);
          }

        });
      },

      //商品单位查询
      editProductUnit () {
        let para = {};

        api.editProductUnit(para).then((res) => {

          let datas = JSON.parse(res.data);
          if(!datas.status){
            if(datas.success){
              //成功
              this.formUnit = datas.data.unit
            }else {
              this.$message.error(datas.message);
            }
          }else{
            if(datas.status == 401){
              this.$router.push('/login');
            }
            this.$message(res.data.msg);
          }

        });
      },


    },
    mounted() {
      this.$nextTick(() => {
        this.productId.id = util.cookieMethod.getCookie("productRowId")
        this.editProductUnit ()
        this.getProduct()
      })
    }
  }
</script>
<style>
    .el-tabs--card > .el-tabs__header .el-tabs__nav{border:none;}
    .el-tabs--card > .el-tabs__header .el-tabs__item.is-active{border-bottom-color:#409EFF;}
    .el-tabs--card > .el-tabs__header .el-tabs__item{border-left:none;}
</style>
